import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MenuEntity } from './entities/menu.entity';
import { FindManyOptions, FindOperators, In, Repository } from 'typeorm';
import { CreateMenuDto } from './dto';
import { generateUUID } from 'src/common/utils/uuid';
import { listToTree } from 'src/common/utils/tree';

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(MenuEntity)
    private readonly menuEntityRep: Repository<MenuEntity>,
  ) {}

  async create(createMenuDto: CreateMenuDto) {
    const menuId = generateUUID();
    let menu = {
      ...createMenuDto,
      menuId,
    };
    return await this.menuEntityRep.save(menu);
  }

  async findListById(menuIds: string[]) {
    return await this.menuEntityRep.find({
      where: {
        menuId: In(menuIds),
      },
      order: {
        orderNum: 'ASC',
      },
    });
  }

  async menuTree(menus: MenuEntity[]) {
    const tree = listToTree<MenuEntity>(
      menus,
      (item) => item.menuId,
      (item) => item.parentId,
    );
    return tree;
  }

  find(condition: FindManyOptions<MenuEntity>) {
    return this.menuEntityRep.find(condition);
  }
}
